package entity

import (
	"fmt"
	"time"

	"gorm.io/gorm"
	"shqsoft.cn/pas3ui/base"
)

//ShCompClieZcld 资产拉动导入
type ShCompClieZcld struct {
	ID   int       `gorm:"AUTO_INCREMENT;primary_key;column:ID"`
	JGDM string    `gorm:"column:JGDM"`
	CUNM string    `gorm:"column:CUNM"`
	DRRQ time.Time `gorm:"column:DRRQ"`
	CUID int       `gorm:"column:CUID"`
}

//TableName
func (ShCompClieZcld) TableName() string {
	return "SH_COMP_CLIE_ZCLD"
}

// BeforeCreate
func (u *ShCompClieZcld) BeforeCreate(tx *gorm.DB) (err error) {
	err = base.CHDB.Raw(`SELECT "CUID" FROM "T_COMP_CLIE" WHERE "ENCD"=? AND "CUNM"=?`, u.JGDM, u.CUNM).Row().Scan(&u.CUID)
	if err != nil {
		err = fmt.Errorf("组织机构代码%s或客户名称%s在系统中不存在！", u.JGDM, u.CUNM)
		return
	}
	//判断是否重复导入
	var count int
	if u.ID == 0 {
		tx.Raw(`SELECT COUNT(*) FROM "SH_COMP_CLIE_ZCLD" WHERE =? AND "DRRQ"=?`, u.CUID, u.DRRQ).Row().Scan(&count)
		if count > 0 {
			err = fmt.Errorf("客户名称:%s,不能重复导入！", u.CUNM)
			return
		}
	}
	return
}

// AfterCreate
func (u *ShCompClieZcld) AfterCreate(tx *gorm.DB) (err error) {
	var (
		count          int
		sqlStr         string
		monthStartTime *time.Time
	)
	tx.Raw(`SELECT COUNT(*) FROM "SH_COMP_CLIE_ZCLD_ZIPPER" WHERE "CUID"=? AND "EDATE"='2099-12-31'`, u.CUID).Row().Scan(&count)
	if count == 0 {
		monthStartTime = base.GetFirstDateOfMonth(&u.DRRQ)
		sqlStr = `INSERT INTO "SH_COMP_CLIE_ZCLD_ZIPPER"("CUID", "SDATE", "EDATE", "ISZC") VALUES(?, ?, '2099-12-31', 1)`
		err = tx.Exec(sqlStr, u.CUID, monthStartTime).Error
		if err != nil {
			return err
		}
	}
	return
}

func ShCompClieZcldAfterImport(tx *gorm.DB, params map[string]string) (err error) {
	prams := params["DRRQ"]
	dtid, _ := time.Parse("2006-01-02", prams[:10])
	dtid = dtid.AddDate(0, -1, 0)
	monthEndTime := base.GetLastDateOfMonth(&dtid)
	sqlStr := `UPDATE "SH_COMP_CLIE_ZCLD_ZIPPER" A LEFT JOIN "SH_COMP_CLIE_ZCLD" B ON A."CUID"=B."CUID" SET A."EDATE"=?
	WHERE B."CUID" IS NULL AND A."EDATE"='2099-12-31'`
	err = tx.Exec(sqlStr, monthEndTime).Error
	if err != nil {
		return err
	}
	tx.Commit()
	base.CHDB.Exec("system reload dictionary pas_olap_nj.DICT_COMP_CLIE_ZCLD_ZIPPER")
	return
}

//ShCompClieZcldEF 返回结构体
func ShCompClieZcldEF() base.EntityFunc {
	return func() interface{} {
		entity := ShCompClieZcld{}
		return &entity
	}
}

//ShCompClieZcldESF 返回结构体数组
func ShCompClieZcldESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []ShCompClieZcld
		return &entities
	}
}

func init() {
	base.SetAfterCallBack("ShCompClieZcld", ShCompClieZcldAfterImport)
	base.DaoPoolObj.Put("ShCompClieZcld", base.NewDefaultDao(ShCompClieZcldEF(), ShCompClieZcldESF(), nil, "my"))
}
